package Maximum;



import java.io.IOException;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class ServerAgent extends Agent{

	private int dataId;
	private float initialTime;
	private float finalTime;
	private float [] data =  new float[3];
	private String [] result =  new String[3];
	
    protected void setup() {
    	data[0] = dataId;
		data[1] = initialTime;
		data[2] = finalTime;
		// Register the sensors-managing service 
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType("sensors-managing");
		sd.setName("JADE-sensors-measure");
		dfd.addServices(sd);
		try 
		{
			DFService.register(this, dfd);
		} catch (FIPAException fe) 
		{
			fe.printStackTrace();
		}
		    
		 // Add the behaviour serving queries from buyer agents
	    addBehaviour(new DataRequestServer());
    }
   
  
	  protected void takeDown() {
	    // Deregister 
	    try {
	      DFService.deregister(this);
	    } catch (FIPAException fe) {
	      fe.printStackTrace();
	    }
	    // Printout a dismissal message
	    System.out.println("Server. agent "+getAID().getName()+" terminating.");
	  }
	  
	  
	  private class DataRequestServer extends CyclicBehaviour {
			public void action() {
				MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
				ACLMessage msg = myAgent.receive(mt);
			    if (msg != null) {
			      // CFP Message received. Process it
			      String message = msg.getContent();
			      ACLMessage reply = msg.createReply();
			      if(data!=null)
			      {
			      reply.setConversationId("sensors-measure");
			      reply.setPerformative(ACLMessage.AGREE);
			      try {
					reply.setContentObject(data);
					
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			      }
			      else 
			      {
			      reply.setPerformative(ACLMessage.REFUSE);
			      reply.setContent("not-available");
			      }
			      myAgent.send(reply);
			    } else {
				    block();
				}
		    }
		  }  
}
